package models

import (
	"errors"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"time"
)

var (
	UserList map[string]*User
)
var (
	SupplierList map[string]*Supplier
)
var (
	MenuList map[string]*Menu
)

func init() {
	UserList = make(map[string]*User)
	u := User{"user_1", "astaxie", "11111",
		Profile{"male", 20, "Singapore", "astaxie@gmail.com"}}
	UserList[u.Id] = &u
	UserList["1"] = &u
	mysqluser := beego.AppConfig.String("mysqluser")
	mysqlpass := beego.AppConfig.String("mysqlpass")
	mysqlurls := beego.AppConfig.String("mysqlurls")
	mysqldb := beego.AppConfig.String("mysqldb")
	orm.RegisterModel(new(Supplier), new(Menu))
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterDataBase("default", "mysql", mysqluser+":"+mysqlpass+"@tcp("+mysqlurls+":3306)/"+mysqldb+"?charset=utf8", 30)
}
func (u *Supplier) TableName() string {
	// db table name
	return "erp_suppliers"
}

type Menu struct {
	Id   int
	Name string
}

func (u *Menu) TableName() string {
	// db table name
	return "ci_menu"
}

type Supplier struct {
	Id   int
	Name string
}
type User struct {
	Id       string
	Username string
	Password string
	Profile  Profile
}

type Profile struct {
	Gender  string
	Age     int
	Address string
	Email   string
}

func AddUser(u User) string {
	u.Id = "user_" + strconv.FormatInt(time.Now().UnixNano(), 10)
	UserList[u.Id] = &u
	return u.Id
}

func GetUser(uid string) (u *User, err error) {
	if u, ok := UserList[uid]; ok {
		return u, nil
	}
	return nil, errors.New("User not exists")
}

func GetAllUsers() map[string]*User {
	return UserList
}
func GetAllSupplier() map[string]*Supplier {
	SupplierList = make(map[string]*Supplier)
	o := orm.NewOrm()
	u := Supplier{Id: 1}
	o.Read(&u)
	SupplierList["supplier"] = &u
	return SupplierList
}
func GetAllMenu() map[string]*Menu {
	MenuList = make(map[string]*Menu)
	o := orm.NewOrm()
	u := Menu{Id: 1}
	o.Read(&u)
	MenuList["Menu"] = &u
	return MenuList
}

func UpdateUser(uid string, uu *User) (a *User, err error) {
	if u, ok := UserList[uid]; ok {
		if uu.Username != "" {
			u.Username = uu.Username
		}
		if uu.Password != "" {
			u.Password = uu.Password
		}
		if uu.Profile.Age != 0 {
			u.Profile.Age = uu.Profile.Age
		}
		if uu.Profile.Address != "" {
			u.Profile.Address = uu.Profile.Address
		}
		if uu.Profile.Gender != "" {
			u.Profile.Gender = uu.Profile.Gender
		}
		if uu.Profile.Email != "" {
			u.Profile.Email = uu.Profile.Email
		}
		return u, nil
	}
	return nil, errors.New("User Not Exist")
}

func Login(username, password string) bool {
	for _, u := range UserList {
		if u.Username == username && u.Password == password {
			return true
		}
	}
	return false
}

func DeleteUser(uid string) {
	delete(UserList, uid)
}
